package com.taldh.springdata;

import com.taldh.springdata.dao.JpaTemplate;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

public class JpaFactoryBean<T extends JpaTemplate> implements FactoryBean<T>, InitializingBean {

    private final Class<?> tClass;
    private T dao;

    public JpaFactoryBean(Class<?> tClass) {
        this.tClass = tClass;
    }

    @Override
    public T getObject() throws Exception {
        return dao;
    }

    @Override
    public Class<?> getObjectType() {
        return tClass;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void afterPropertiesSet() throws Exception {
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTargetClass(tClass);
        proxyFactory.setProxyTargetClass(false);
        proxyFactory.addAdvice((MethodInterceptor) methodInvocation -> {
            System.out.println("开始执行方法："+methodInvocation.getMethod());
            Object result = null;
            switch (methodInvocation.getMethod().getName()) {
                case "insertMethod":
                    System.out.println("执行数据库的insert的操作");
                    result = 1;
                    break;
                case "findMethod":
                    System.out.println("执行数据库的find方法的操作");
                    result = 2;
                    break;
                case "deleteMethod":
                    System.out.println("执行数据库的delete方法的操作");
                    result = 3;
                    break;
                case "updateMethod":
                    System.out.println("执行数据库的update方法的操作");
                    result = 4;
                    break;
                default:
                    System.out.println("执行自定义方法的操作");
                    result = "Hello Jpa";
            }
            System.out.println("执行的结果："+result);
            return result;
        });

        dao = (T) proxyFactory.getProxy();
    }
}
